<template>
  <view>
    <uni-popup ref="loginDialogRef" type="dialog">
      <uni-popup-dialog
        title="请先登录你的账号"
        cancelText="取消"
        confirmText="立即登录"
        content="登录后可创建/查看跑团"
        @close="handleLoginClose"
        @confirm="handleLoginConfirm"
      ></uni-popup-dialog>
    </uni-popup>
    <uni-popup ref="alertDialogRangeRef" type="dialog">
      <uni-popup-dialog
        :title="state.title"
        :cancelText="state.cancelText"
        :confirmText="state.confirmText"
        :content="state.content"
        @close="handleClose"
        @confirm="handleConfirm"
      ></uni-popup-dialog>
    </uni-popup>
    <!-- 提示窗示例 -->
    <uni-popup ref="alertDialog" type="dialog">
      <uni-popup-dialog
        cancelText="取消"
        confirmText="确定"
        title=""
        @confirm="dialogConfirmTrans"
        @close="dialogClose"
      >
        <view class="dialog-content">
          <view class="label">{{ state.joinGroupMessage }}</view>
        </view>
      </uni-popup-dialog>
  </uni-popup>
  </view>
</template>

<script setup name="PictureUpload">
import { onLaunch, onShow, onHide, onUnload } from "@dcloudio/uni-app";
import { reactive, ref, toRefs, watch, onMounted, getCurrentInstance, nextTick } from 'vue';
import * as API from "../../api/api"
import { storeToRefs } from "pinia";
import { useRunInfoStore } from "../../store/runInfo";
import { useGroupStore } from "@/store/group";
import { userLoginStore } from "../../store/userLogin";
const useGroupData = useGroupStore()
const useRunInfoData = useRunInfoStore()
const userLoginData = userLoginStore()
const { proportionShow, initStatus, timerNum, centerDistance, runType } = storeToRefs(useRunInfoData)
const { groupInfo } = storeToRefs(useGroupData)
const appInstance = getCurrentInstance().proxy
const props = defineProps({
  tipTxt: {
    type: String,
    default: "请阅读并勾选用户协议"
  },
  title: {
    type: String,
    default: '创建跑团'
  },
  groupName: {
    type:String,
    default: ''
  },
  type: {
    type: String,
    default: 'create'
  },
  uuid: {
    type: String,
    default: ''
  },
  getRankingData: Function
})

const { tipTxt, title, groupName, type, uuid }  = toRefs(props)
const alertDialogRangeRef = ref(null);
const loginDialogRef = ref(null);
const alertDialog = ref(null);

const state = reactive({
  title: "",
  cancelText: "",
  confirmText: "",
  content: "",
	userInfo: null,
})

// 入团判断
const groupJudgeJoin = () => {
  let params = {
    userId: state.userInfo?.customers?.customerId,
    groupId: groupInfo?.value?.groupId || state.joinGroupId,
  };
  console.log("入团判断参数===", params);
  API.groupJudgeJoin(params)
    .then((res) => {
      if (res.code === 0) {
        state.joinType = res.data;
        console.log("入团返回参数", res.data, state.joinType);
        onJudgePop();
      }
    })
    .catch((err) => {});
};

// 入团弹窗
const onJudgePop = () => {
  console.log("state.joinType", state.joinType);
  state.title = "";
  if (state.joinType && state.joinType !== 1000) {
    // 无团已满员
    if (state.joinType === 1001) {
      state.cancelText = "加入其他跑团";
      state.confirmText = "创建跑团";
      state.content = "该跑团已满员，您可以自己创建跑团或加入其他跑团";
    }
    // 有团且是团员
    if (state.joinType === 1002) {
      state.cancelText = "取消";
      state.confirmText = "确定加入";
      state.content = "您已加入其他跑团，确认加入新跑团将从原跑团移出";
    }
    // 有团且是团长且团人数>1
    if (state.joinType === 1003) {
      state.cancelText = "知道了";
      state.confirmText = "";
      state.content = "您已有自己的跑团了，暂时不能加入该跑团";
    }
    // 有团且是团长且团人数=1
    if (state.joinType === 1004) {
      state.cancelText = "取消";
      state.confirmText = "确定加入";
      state.content = "确认加入该跑团？加入后您自己的跑团将会解散";
    }
    if (state.joinType === 1005) {
      state.joinGroupMessage = "用户信息不完整，请完善个人资料";
      alertDialog.value.open();
      return;
    }
    alertDialogRangeRef.value.open();
  } else {
    onJoinGroup();
  }
};

// 入团接口调用
const onJoinGroup = () => {
  let params = {
    userId: state.userInfo?.customers?.customerId,
    groupId: groupInfo?.value?.groupId || state.joinGroupId,
    joinTypeCode: state.joinType,
  };
  API.joinGroup(params)
    .then((res) => {
      if (res.code === 0) {
        uni.showToast({
          title: "您已成功加入该跑团",
          icon: "none",
        });
        useGroupData.onGetGroupInfo().then(res => {
          useGroupData.onGetGroupMemberList()
        })
      } else if (res.code === 205) {
        state.joinGroupMessage = res.message;
      } else {
        uni.showToast({
          title: res.message,
          icon: "none",
        });
      }
    })
    .catch((err) => {});
};

const handleLoginConfirm = () => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  userLoginData.setRedirectUrl(currentPage.$page.fullPath);
  uni.navigateTo({
    url: "/pages/login/login",
  });
};

const handleLoginClose = () => {
  loginDialogRef?.value?.close();
};

const dialogConfirmTrans = () => {
  uni.navigateTo({
    url: "/pages/personInfo/personInfo",
  });
};

const handleConfirm = () => {
  alertDialogRangeRef?.value?.close();
  state.hidePop = true;
  uni.setStorageSync("hidePop", state.hidePop);
  // 无团已满员
  if (state.joinType === 1001) {
    // 确定-创建跑团
    gotoLogin(1);
  }
  // 有团且是团员
  if (state.joinType === 1002) {
    // 确定-退出原团加入其他团
    onJoinGroup();
  }
  // 有团且是团长且团人数>1
  if (state.joinType === 1003) {
  }
  // 有团且是团长且团人数=1
  if (state.joinType === 1004) {
    // 确定-解散原团加入其他团
    onJoinGroup();
  }
  if (state.joinType === 1005 || !state.userInfo?.customers?.customerName) {
    uni.navigateTo({
      url: "/pages/personInfo/personInfo",
    });
  }
};

const handleClose = () => {
  alertDialogRangeRef?.value?.close();
  state.hidePop = true;
  uni.setStorageSync("hidePop", state.hidePop);
  // 无团已满员
  if (state.joinType === 1001) {
    // 确定-加入其他跑团-扫二维码进团
    onScanCode();
  }
  // 有团且是团员
  if (state.joinType === 1002) {
  }
  // 有团且是团长且团人数>1
  if (state.joinType === 1003) {
  }
  // 有团且是团长且团人数=1
  if (state.joinType === 1004) {
  }
};

const onShowLoginPop = () => {
  loginDialogRef?.value?.open();
};

const onShowPersonPop = () => {
  state.joinGroupMessage = "用户信息不完整，请完善个人资料";
  alertDialog.value.open();
};



onShow(() => {
	state.userInfo = uni.getStorageSync("userInfo") ? JSON.parse(uni.getStorageSync("userInfo")) : null
  state.isClickTwo = true
})

watch(() => initStatus.value, (newValue, oldValue) => {

}, {imediate: true})

defineExpose({
  groupJudgeJoin,
  onShowLoginPop,
  onShowPersonPop
})

</script>

<style lang="scss">
	.popup-content{
		width: 100vw;
		height: 720rpx;
		padding: 32rpx;
		box-sizing: border-box;
		.popup-header{
			display: flex;
			justify-content: space-between;
			.header-title{
				font-weight: 500;
				font-size: 36rpx;
				color: #1C1C1E;
			}
			.header-close{
				width: 56rpx;
				height: 56rpx;
			}
		}
	}
	.popup-picture{
		display: flex;
		justify-content: center;
		.item-picture{
			width: 180rpx;
			height: 180rpx;
			background: #F7F8FA;
			border-radius: 16rpx;
			position: relative;
			text-align: center;
			margin-top: 80rpx;
      border-radius: 16rpx;
      overflow: hidden;
			&:first-child{
				margin-right: 84rpx;
			}
			.avart{
				width: 100%;
				height: 100%;
			}
			.icon-photo{
				width: 52rpx;
				height: 44rpx;
				margin-top: 60rpx;
			}
			.item-tip{
				width: 180rpx;
				height: 44rpx;
				background: rgba(0,0,0,0.5);
				border-radius: 0rpx 0rpx 16rpx 16rpx;
				position: absolute;
				bottom: 0;
				left: 0;
				font-size: 20rpx;
				color: #fff;
				text-align: center;
				line-height: 44rpx;
				display: flex;
				justify-content: center;
				align-items: center;
			}
		}
	}
	.group-name{
		display: flex;
		align-items: center;
		margin: 72rpx 0 60rpx;
		label{
			font-size: 32rpx;
			color: #1C1C1E;
		}
	}
	.icon-requied{
		font-size: 32rpx;
		color: #F55858;
	}
</style>
